package org.mogu.tools;

import gif.GifAction;
import gif.GifDecoder;
import gif.GifDrawable;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.mogu.R;
import org.mogu.Welcome;
import org.mogu.staticvalue.Convert;

import org.mogu.control.ImagesStruct;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.Callback;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.widget.TextView;

class GifCallback implements Callback{
	private Handler handler = new Handler();  
	GifDrawable b;
	TextView label=null;
	long when;
	public GifCallback(){
		//label=l;
	}
	@Override
	public void invalidateDrawable(Drawable who) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void scheduleDrawable(Drawable who, Runnable what, long whe) {
		// TODO Auto-generated method stub
		b=(GifDrawable)who;
		when=whe;
		new Thread(){
			public void run(){
				
				b.changeGif();
				label.append(" ");
	            handler.postDelayed(this, when);  
			}
		}.start();
		
	}

	@Override
	public void unscheduleDrawable(Drawable who, Runnable what) {
		// TODO Auto-generated method stub
		
	}
}
public class Imgtools implements GifAction {

	static String imgreg="\\[\\*[A-Za-z]*/[-0-9A-Z]*/[_A-Za-z0-9]*\\*\\]";//图片过滤正则
	static Pattern pattern=Pattern.compile(imgreg);
	public static Welcome welcome;
//	public static Map<String, GifDrawable> gifMap=new HashMap<String, GifDrawable>();
	public static GifDrawable[] gifarr=new GifDrawable[3];
	public static int index=0;
	public static long deply=300;
	private static Handler handler = new Handler();  
	private static boolean isRuning=false; 
	
	
	public static void gifRun(){
		new Thread(){
			public void run(){
				
				//b.changeGif();
				for(int i=0;i<gifarr.length;i++){
					if(gifarr[i]==null){
						continue;
					}else{
						gifarr[i].changeGif();
					}
				}
				if(gifarr[index]!=null){
//					gifarr[0].lbl.append(" ");
					gifarr[index].lbl.setText(gifarr[index].lbl.getText());
				}else{
					deply=2000;
				}
				
	            handler.postDelayed(this, deply);  
			}
		}.start();
		isRuning=true;
	}
	
	public static void clearGif(){
		for(int i=0;i<gifarr.length;i++){
				gifarr[i]=null;
		}
	}
	
	public static String hasImg(String content){
		Matcher matcher=pattern.matcher(content);
		
		while(matcher.find()){
			String imgstr=matcher.group();
			int imgnum=imgstr.indexOf("/");
			int imgnum2=imgstr.indexOf("/",imgnum+1);
			String  imgcodestr=imgstr.substring(imgnum+1, imgnum2);
			String  imgcodestr2=imgstr.substring(imgnum2+1, imgstr.length()-2);
			String myJpgPath = Convert.picPath+imgcodestr+imgcodestr2+".jpg";
			File f=new File(myJpgPath);
			if(!f.exists()){
				content=content.replace(imgstr, "");
			}
			
		}
		return content;
	}
	public static String outImg(String content){
		Matcher matcher=pattern.matcher(content);
		
		while(matcher.find()){
			String imgstr=matcher.group();
			//int imgnum=imgstr.indexOf("/");
			//String  imglibstr=imgstr.substring(2, imgnum);
			//String  imgcodestr=imgstr.substring(imgnum+1, imgstr.length()-2);
			//String myJpgPath = Convert.picPath+imgcodestr+".jpg";
			content=content.replace(imgstr, "");
			
			
		}
		return content;
	}
	
	public static SpannableString getContent(String content){
		return getContent(content,null);
	}
	
	public static SpannableString getContent(String content,TextView lbl){
//		if(lbl!=null){
//			gifarr=new GifDrawable[3];
//		}
		
		//String myJpgPath = Convert.picPath+"223.jpg";
		//String content=hasImg(contents);
		if(content==null){
			content="";
		}
		Matcher matcher=pattern.matcher(content);
		SpannableString spannableString = new SpannableString(content);
		int p=0;
		 BitmapFactory.Options options = new BitmapFactory.Options(); 
         
         // 获取这个图片的宽和高 
         
         
		while(matcher.find()){
			String imgstr=matcher.group();
			int imgnum=imgstr.indexOf("/");
			int imgnum2=imgstr.indexOf("/",imgnum+1);
			String  imgcodestr=imgstr.substring(imgnum+1, imgnum2);
			String  imgcodestr2=imgstr.substring(imgnum2+1, imgstr.length()-2);
			String myJpgPath = Convert.picPath+imgcodestr+imgcodestr2;
			try{
				Bitmap bm=null;
				GifDrawable d=null;
				File f=new File(myJpgPath+".jpg");
				if(!f.exists()){
					f=new File(myJpgPath+".gif");
					if(f.exists()){
						if(lbl==null){
							options.inJustDecodeBounds = true; 
							bm = BitmapFactory.decodeFile(myJpgPath+".gif", options);
							options.inJustDecodeBounds = false; 
					         //计算缩放比 
					         int be = (int)(options.outWidth / (float)Convert.picWidth); 
					         if (be <= 0) 
					              be = 1; 
					         options.inSampleSize = be;
					         bm = BitmapFactory.decodeFile(myJpgPath+".gif", options);
						}else{
							bm=null;
							FileInputStream fin = new FileInputStream(myJpgPath+".gif");
							int length = fin.available();
				        	byte[] buffer = new byte[length];
				        	fin.read(buffer);											        	 
				        	fin.close();   
				        	GifDecoder gifDecoder = null;
				        	gifDecoder = new GifDecoder(buffer,new Imgtools());
				        	gifDecoder.start();
			        		
			        		while(bm ==null){											        		
				        		bm = gifDecoder.getImage();
				        	}
//			        		if(deply>gifDecoder.next().delay){
			        			deply=new Integer(gifDecoder.next().delay).longValue();
//			        		}
			        		d = new GifDrawable(welcome.getResources(),bm);
							d.setGifDecoder(gifDecoder,lbl);
							d.setBounds(6, 6, (int)(d.getIntrinsicWidth()*1.2+6), (int)(d.getIntrinsicHeight()*1.2+6));	
							index++;
							if(index>=gifarr.length){
								index=0;
							}
							gifarr[index]=d;
							
							
//							for(int i=0;i<gifarr.length;i++){
//								if(gifarr[i]==null){
//									gifarr[i]=d;
//									break;
//								}
//							}
						}
					}else{
						if(lbl==null){
							bm=BitmapFactory.decodeResource(welcome.getResources(), R.drawable.noimg);
						}else{
							bm=null;
							InputStream fin = welcome.getResources().openRawResource(R.drawable.nogif);
							int length = fin.available();
				        	byte[] buffer = new byte[length];
				        	fin.read(buffer);											        	 
				        	fin.close();   
				        	GifDecoder gifDecoder = null;
				        	gifDecoder = new GifDecoder(buffer,new Imgtools());
				        	gifDecoder.start();
			        		
			        		while(bm ==null){											        		
				        		bm = gifDecoder.getImage();
				        	}
//			        		if(deply>gifDecoder.next().delay){
			        			deply=new Integer(gifDecoder.next().delay).longValue();
//			        		}
			        		d = new GifDrawable(welcome.getResources(),bm);
							d.setGifDecoder(gifDecoder,lbl);
							d.setBounds(6, 6, (int)(d.getIntrinsicWidth()*1.2+6), (int)(d.getIntrinsicHeight()*1.2+6));	
							index++;
							if(index>=gifarr.length){
								index=0;
							}
							gifarr[index]=d;
//							for(int i=0;i<gifarr.length;i++){
//								if(gifarr[i]==null){
//									gifarr[i]=d;
//									break;
//								}
//							}
						}
								
					}
					
				}else{
					options.inJustDecodeBounds = true; 
					bm = BitmapFactory.decodeFile(myJpgPath+".jpg", options);
					options.inJustDecodeBounds = false; 
			         //计算缩放比 
			         int be = (int)(options.outWidth / (float)Convert.picWidth); 
			         if (be <= 0) 
			              be = 1; 
			         options.inSampleSize = be;
			         bm = BitmapFactory.decodeFile(myJpgPath+".jpg", options);
				}
				
				
				ImageSpan imageSpan;
				if(d!=null){
					imageSpan= new ImageSpan(d);
				}else{
//					BitmapDrawable drawable=new BitmapDrawable(bm);
//					drawable.setBounds(6, 6, (int)(drawable.getIntrinsicWidth()*1.2+6), (int)(drawable.getIntrinsicHeight()*1.2+6));	
//					imageSpan= new ImageSpan(drawable);
					imageSpan= new ImageSpan(bm);
				}
				
			      spannableString.setSpan(imageSpan, content.indexOf(imgstr,p), content.indexOf(imgstr,p)+imgstr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			      p=content.indexOf(imgstr, p)+imgstr.length();
			}catch(Exception e){
				Log.e("Img", "Not "+imgnum);
			}
	      
	      
		}
		
		
      if(!isRuning){
    	  gifRun();
      }
		
      return spannableString;
	}
	
	public static Bitmap getImage(String picname){
		Bitmap bm=null;
		String myJpgPath = Convert.picPath+picname;
		BitmapFactory.Options options = new BitmapFactory.Options(); 
		try{
			
//			GifDrawable d=null;
			File f=new File(myJpgPath+".jpg");
			if(!f.exists()){
				f=new File(myJpgPath+".gif");
				if(f.exists()){
						options.inJustDecodeBounds = true; 
						bm = BitmapFactory.decodeFile(myJpgPath+".gif", options);
						options.inJustDecodeBounds = false; 
				         //计算缩放比 
				         int be = (int)(options.outWidth / (float)Convert.picWidth); 
				         if (be <= 0) 
				              be = 1; 
				         options.inSampleSize = be;
				         bm = BitmapFactory.decodeFile(myJpgPath+".gif", options);
						
				}else{
						bm=BitmapFactory.decodeResource(welcome.getResources(), R.drawable.noimg);
							
				}
				
			}else{
				options.inJustDecodeBounds = true; 
				bm = BitmapFactory.decodeFile(myJpgPath+".jpg", options);
				options.inJustDecodeBounds = false; 
		         //计算缩放比 
		         int be = (int)(options.outWidth / (float)Convert.picWidth); 
		         if (be <= 0) 
		              be = 1; 
		         options.inSampleSize = be;
		         bm = BitmapFactory.decodeFile(myJpgPath+".jpg", options);
			}
			
			
			
		}catch(Exception e){
		}
		return bm;
	}
	
	public void parseOk(boolean parseStatus,int frameIndex){
	    }
	static GifDecoder[]  arrGifDecoder= new GifDecoder[50];
	static ImagesStruct[] arrEditImgs = new ImagesStruct[50];	
//	public static void getContent2(String content){
//		for(int loop=0;loop<arrGifDecoder.length;loop++){
//			arrGifDecoder[loop]=null;			
//		}
//		for(int loop=0;loop<arrEditImgs.length;loop++){
//			ImagesStruct imgStruct = arrEditImgs[loop];
//			if(imgStruct==null)
//				break;				
//			
//				//��ʼgif
//				try{
//					FileInputStream fin = new FileInputStream(path);
//		        	int length = fin.available();
//		        	byte[] buffer = new byte[length];
//		        	fin.read(buffer);											        	 
//		        	fin.close();   
//		        	GifDecoder gifDecoder = null;
//		        	gifDecoder = new GifDecoder(buffer,new Imgtools());
//		        	gifDecoder.start();
//	        		Bitmap bmp = null;
//	        		while(bmp ==null){											        		
//		        		bmp = gifDecoder.getImage();
//		        	}
//	        		for(int l=0;l<arrGifDecoder.length;l++){
//	        			if(arrGifDecoder[l]==null){
//	        				arrGifDecoder[l] = gifDecoder;
//	        				break;
//	        			}
//	        		}
//	        		
//				}catch(Exception e){		
//					e.printStackTrace();
//				}
//			}			
//		
//		isRun =true;
//		DrawThread dt = new DrawThread();
//		dt.start();	
//	}
//	private class DrawThread extends Thread{	
//    	public void run(){
//    		try{
//    		if(arrGifDecoder[0]==null){
//    			setEditContent();
//    			return;
//    		}
//    		long sp=1;
//    		while(isRun){
//    			for(int loop =0;loop<arrGifDecoder.length;loop++){
//    				if(arrGifDecoder[loop]==null)
//    					break;
//    				GifFrame frame =  arrGifDecoder[loop].next();
//    				sp = frame.delay;
//    				Bitmap bmp = frame.image;
//    				changeArrGif(bmp,loop); 				
//    			}
//    			//�ж��ı����Ƿ��������µ�����
//    			Message message = new Message();
//    			message.what = 4;
//    			mHandler.sendMessage(message);  
//    			SystemClock.sleep(sp);
//    		}
//    		}catch(Exception e){
//    			e.printStackTrace();
//    		}
//    	}
//    }	
//	//�޸��õ���gifͼƬ����	
//	private void changeArrGif(Bitmap bmp,int index){
//		int l =0;		
//		for(int loop =0;loop<Used.arrEditImgs.length;loop++){
//			if(Used.arrEditImgs[loop].suffix.equals("gif")){
//				l++;
//				if(l==index+1){	
//					ImagesStruct imgStruct = Used.arrEditImgs[loop];
//					imgStruct.printBmp = bmp;
//					Used.arrEditImgs[loop] = imgStruct;					
//					break;
//				}
//			}			
//		}
//	}
//	//����ַ����ͼ������
//	private void setEditContent(){
//		//����ͼƬ		
//		if(Used.strReplyContent.equals(""))
//			return;
//		if(!Used.strReplyContent.contains("[*")){		
//			eContent.setText(Used.strReplyContent);
//			return;
//		}
//		String str = Used.strReplyContent;
//		eContent.setText("");
//		while(str.indexOf("[*")>=0){
//			int index1 = str.indexOf("[*");
//			int index2 = str.indexOf("*]");
//			String str1 = str.substring(0,index1);
//			String str2 = str.substring(index2+2,str.length());
//			String str3 = str.substring(index1+2,index2);
//			String str4 = str.substring(index1,index2+2);
//			//�����õ�ͼƬ·��
//			str3 = str3.replace("/", strSplit);
//			String[] arr = str3.split(strSplit);
//			String id = arr[1];
//			Bitmap bmp =null;
//			for(int loop=0;loop<Used.arrEditImgs.length;loop++){
//				ImagesStruct imgStruct = Used.arrEditImgs[loop];
//				if(imgStruct.id.equals(id)){				
//					bmp = imgStruct.printBmp;					
//					break;
//				}
//			}
//			SpannableString ss = new SpannableString(str4);
//			Drawable d = new BitmapDrawable(bmp);
//			d.setBounds(6, 6, (int)(d.getIntrinsicWidth()*1.2+6), (int)(d.getIntrinsicHeight()*1.2+6));			
//			ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
//			ss.setSpan(span, 0, ss.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//			eContent.append(str1);
//			eContent.append(ss);
//			if(!str2.contains("[*")){
//				eContent.append(str2);
//				break;
//			}
//			str = str2;
//		}
//		Editable etext = eContent.getText();	    
//		if(Used.editCurIndex ==-1){
//			Selection.setSelection(etext, etext.length());
//		}else{
//			Selection.setSelection(etext, Used.editCurIndex);
//		}
//	}
}
